package com.aube.plugin.gallery.preview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.utils.ImageParamUtils;
import com.huyn.baseframework.utils.Utils;

/**
 * Created by huyaonan on 16/9/13.
 */
public class GalleryItem extends LinearLayout {

    private ImageView mImg;

    public GalleryItem(Context context) {
        this(context, null);
    }

    public GalleryItem(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GalleryItem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackgroundColor(Color.BLUE);
    }

    public void attachImg(int index, String url, OnImageGetter iGetter) {
        if(getChildCount() > 0) {
            mImg = (ImageView) getChildAt(0);
        } else {
            mImg = iGetter.getImgView();
            GalleryListView.Size size = iGetter.getSize(url);
            addView(mImg, new LayoutParams(size.width, size.height));
            iGetter.markImgAdded(index);
        }
        ImageLoader.getInstance(getContext()).preloadBitmap(ImageParamUtils.getPicList(url), new ImageLoader.IPreloadCallback<Bitmap>() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                if(bitmap != null) {
                    mImg.setImageBitmap(bitmap);
                    bitmap = null;
                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    public ImageView getImageView() {
        return mImg;
    }

    public void setBackground(Bitmap bitmap) {
        if(bitmap != null)
            setBackgroundDrawable(new BitmapDrawable(bitmap));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

//        if(mImg != null) {
//            mImg.measure(widthMeasureSpec, heightMeasureSpec);
//        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if(mImg != null) {
            mImg.layout(0, 0, getWidth(), getHeight());
        }
    }

    public ImageView detachImg() {
        if(getChildCount() > 0) {
            Utils.sysout("==========remove img...");
            mImg = null;
            ImageView view = (ImageView) getChildAt(0);
            view.setImageDrawable(null);
            removeAllViews();
            return view;
        }
        return null;
    }

    public interface OnImageGetter {
        public ImageView getImgView();
        public GalleryListView.Size getSize(String url);
        public void markImgAdded(int index);
    }

}
